﻿
// DETECTDlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "DETECT.h"
#include "DETECTDlg.h"
#include "afxdialogex.h"

#include "headfile.h"
#include "DETECTor.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// 全局变量
DETECTor detector;
WINDOWSIZE wds;
cv::Mat frame;
CImage cimage;

HANDLE hThread1;
HANDLE hThread2;

auto t_shot1 = std::chrono::high_resolution_clock::now();
auto t_shot2 = std::chrono::high_resolution_clock::now();

char str[64] = { '0' };
std::string savepath;

int nChars;
int time_in_milliseconds;
int frame_count = 0;
int last_shot = 0;
int last_fram_count = 0;
int fps = 0;
int ang = 0;
int collectDatacount = 0;

int gb_AVG[2] = { 0 };
int gl_AVG[2] = { 0 };
float center_AVG = 0;
int relative_AVG[4] = { 0 };
float error_AVG[2] = { 0 };

std::chrono::duration<double> diff;
std::string file_name;
std::string nowTime;

bool firstOpen = false;
bool detectCheck = false;
bool isFullscreen = false;
bool isRot = false;
bool openCollect = false;
bool firstLarge = true;

bool RUNNING = true;

CRect rect_show;
CDC* pDc;

void CDETECTDlg::Getframe() {
	while (RUNNING) {

		bool get = detector.getFrame();
	}
}

void CDETECTDlg::Show() {

	std::string s_yuan = "源分辨率：" + std::to_string(wds.inputW) + " * " + std::to_string(wds.inputH);
	CString cs_yuan = CA2T(s_yuan.c_str());
	GetDlgItem(IDC_yuan)->SetWindowText(cs_yuan);

	while (RUNNING) {

		// 等待缓冲区
		if (detector.frame_count < 100) {
			Sleep(100);
			continue;
		}

		detector.image = detector.ooimg[(detector.frame_count - 1) % 100];

		//resize(detector.image, detector.image, dsize, 0, 0, cv::INTER_AREA);
		// 要缩小图片，一般来说最好的插值方法是 cv.INTER_AREA，而要放大一张图片的话，
		// 一般来说效果最好的是 cv.INTER_CUBIC （速度慢）或者 cv.INTER_LINEAR （速度快一些但结果仍然不错）

		// 检测按钮状态为开
		if (detectCheck) {
			if (firstOpen == true) {
				firstOpen = false;
				detector.frame_count = 0;
			}

			if (detector.cameraID == -1 && detector.isCamera == true) {
				cv::cvtColor(detector.image, detector.image, cv::ColorConversionCodes::COLOR_BayerGB2RGB);
			}
			else {
				if (detector.image.channels() == 1) {
					cv::cvtColor(detector.image, detector.image, CV_GRAY2RGB);
				}
			}
			if (ang != 0) {
				detector.image = Rot(detector.image, ang);
			}
			isRot = true;

			detector.detectGL();
			detector.detectGB();
			detector.reprocess();

			std::string s_gl = "光阑中心：" + std::to_string(detector.xm_GL_Mean) + " , " + std::to_string(detector.ym_GL_Mean);
			std::string s_gb = "光斑中心：" + std::to_string(detector.xm_GB_Mean) + " , " + std::to_string(detector.ym_GB_Mean);
			std::string s_center = "中心点距离：" + std::to_string(powf(powf(detector.xm_GL_Mean - detector.xm_GB_Mean, 2) + powf(detector.ym_GL_Mean - detector.ym_GB_Mean, 2), 0.5)).substr(0, 5);
			std::string s_relative = "相对位置：" + std::to_string(detector.xx2_Mean) + " / " + std::to_string(detector.xx1_Mean) + " , " + std::to_string(detector.yy2_Mean) + " / " + std::to_string(detector.yy1_Mean);
			std::string s_error = "检测误差：" + std::to_string(detector.xx_Delta_Mean).substr(0, 6) + " , " + std::to_string(detector.yy_Delta_Mean).substr(0, 6);

			CString cs_gb = CA2T(s_gb.c_str());
			CString cs_gl = CA2T(s_gl.c_str());
			CString cs_center = CA2T(s_center.c_str());
			CString cs_relative = CA2T(s_relative.c_str());
			CString cs_error = CA2T(s_error.c_str());

			GetDlgItem(IDC_gb)->SetWindowText(cs_gb);
			GetDlgItem(IDC_gl)->SetWindowText(cs_gl);
			GetDlgItem(IDC_center)->SetWindowText(cs_center);
			GetDlgItem(IDC_relative)->SetWindowText(cs_relative);
			GetDlgItem(IDC_error)->SetWindowText(cs_error);

			if (openCollect) {
				gb_AVG[0] += detector.xm_GB_Mean;
				gb_AVG[1] += detector.ym_GB_Mean;

				gl_AVG[0] += detector.xm_GL_Mean;
				gl_AVG[1] += detector.ym_GL_Mean;

				center_AVG += powf(powf(detector.xm_GL_Mean - detector.xm_GB_Mean, 2) + powf(detector.ym_GL_Mean - detector.ym_GB_Mean, 2), 0.5);

				relative_AVG[0] += detector.xx2_Mean;
				relative_AVG[1] += detector.xx1_Mean;
				relative_AVG[2] += detector.yy2_Mean;
				relative_AVG[3] += detector.yy1_Mean;
				
				error_AVG[0] += detector.xx_Delta_Mean;
				error_AVG[1] += detector.yy_Delta_Mean;

				//打开文件
				std::ofstream outputFile(file_name, std::ios::app); // app是追加写入，out是覆盖写入
				//第一次打开，写入头信息数据
				if (collectDatacount == 0) {
					str[64];
					nChars = GetDlgItemText(IDC_channel, str, _countof(str));
					str[nChars] = '\0';
					std::string channel(str);
					nChars = GetDlgItemText(IDC_ID, str, _countof(str));
					str[nChars] = '\0';
					std::string ID(str);
					nChars = GetDlgItemText(IDC_person, str, _countof(str));
					str[nChars] = '\0';
					std::string person(str);

					outputFile << "------【时间】" + nowTime << std::endl;
					outputFile << "------【编号】" + ID << std::endl;
					outputFile << "------【通道】" + channel << std::endl;
					outputFile << "------【人员】" + person << std::endl;
					outputFile << "------【数据】20条"
						<< std::endl;
				}
				outputFile << cs_gb + "\t\t" + cs_gl + "\t\t" + cs_center + "\t\t" + cs_relative + "\t\t" + cs_error
					<< std::endl;

				collectDatacount++;
				if (collectDatacount >= 20) {
					int Nc = 20;
					std::string s_gb_AVG = "光斑中心：" + std::to_string(gb_AVG[0] / Nc) + " , " + std::to_string(gb_AVG[1] / Nc);
					std::string s_gl_AVG = "光阑中心：" + std::to_string(gl_AVG[0] / Nc) + " , " + std::to_string(gl_AVG[1] / Nc);
					std::string s_center_AVG = "中心点距离：" + std::to_string(center_AVG / float(Nc)).substr(0, 5);
					std::string s_relative_AVG = "相对位置：" + std::to_string(relative_AVG[0] / Nc) + " / " + std::to_string(relative_AVG[1] / Nc) + " , " + std::to_string(relative_AVG[2] / Nc) + " / " + std::to_string(relative_AVG[3] / Nc);
					std::string s_error_AVG = "检测误差：" + std::to_string(error_AVG[0] / float(Nc)).substr(0, 6) + " , " + std::to_string(error_AVG[1] / float(Nc)).substr(0, 6);

					CString cs_gb_AVG = CA2T(s_gb_AVG.c_str());
					CString cs_gl_AVG = CA2T(s_gl_AVG.c_str());
					CString cs_center_AVG = CA2T(s_center_AVG.c_str());
					CString cs_relative_AVG = CA2T(s_relative_AVG.c_str());
					CString cs_error_AVG = CA2T(s_error_AVG.c_str());

					outputFile << "------【均值】"
						<< std::endl;
					outputFile << cs_gb_AVG + "\t\t" + cs_gl_AVG + "\t\t" + cs_center_AVG + "\t\t" + cs_relative_AVG + "\t\t" + cs_error_AVG
						<< std::endl;

					MessageBox(_T("保存成功"), _T("提示"), MB_OK | MB_ICONINFORMATION);

					//数据重置
					openCollect = false;
					collectDatacount = 0;

					gb_AVG[0] = 0;
					gb_AVG[1] = 0;

					gl_AVG[0] = 0;
					gl_AVG[1] = 0;

					center_AVG = 0;

					relative_AVG[0] = 0;
					relative_AVG[1] = 0;
					relative_AVG[2] = 0;
					relative_AVG[3] = 0;

					error_AVG[0] = 0;
					error_AVG[1] = 0;
				}

				// 关闭文件  
				outputFile.close();
			}
		}
		else {
			firstOpen = true;
			isRot = false;
		}

		// 显示分辨率实时更新
		std::string s_yulan = "显示分辨率：" + std::to_string(wds.showW) + " * " + std::to_string(wds.showH);
		CString cs_yulan = CA2T(s_yulan.c_str());
		GetDlgItem(IDC_yulan)->SetWindowText(cs_yulan);

		//在预览窗口显示
		cv::Mat mimage = detector.image;
		GetDlgItem(IDC_SHOW)->GetClientRect(rect_show);
		float wR = rect_show.Width() * 1.0;
		float hR = rect_show.Height() * 1.0;
		float ratio = 2832.0 / 2840.0;

		if (wR / hR < ratio) {
			hR = wR / ratio;
			rect_show.bottom = int(rect_show.top + hR);
		}
		else {
			wR = hR * ratio;
			rect_show.right = int(rect_show.left + wR);
		}

		// 显示
		wds.showW = int(wR);
		wds.showH = int(hR);

		// 解决最小化窗口的bug
		if (wds.showW * wds.showH) {
			resize(mimage, mimage, { wds.showW, wds.showH}, 0, 0, cv::INTER_CUBIC);
		}

		if (!isRot) {
			if (ang != 0) {
				mimage = Rot(mimage, ang);
			}
		}

		MatToCImage(mimage, cimage);
		cimage.Draw(pDc->m_hDC, rect_show);
		cimage.Destroy();

		// 帧率处理
		frame_count++;
		t_shot2 = std::chrono::high_resolution_clock::now();
		diff = t_shot2 - t_shot1;
		int f_in = frame_count - last_shot;
		if (f_in > 10) {
			time_in_milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(diff).count();
			time_in_milliseconds = time_in_milliseconds < 1 ? 1 : time_in_milliseconds;
			fps = f_in * 1000 / time_in_milliseconds;

			t_shot1 = t_shot2;
			last_shot = frame_count;
			if (fps > 0) {
				//SetDlgItemInt(IDC_zsl2, fps);
				std::string shows = "显示帧率：" + std::to_string(fps);
				CString cshows = CA2T(shows.c_str());
				GetDlgItem(IDC_zsl2)->SetWindowText(cshows);
			}
		}

	}

}

UINT Show_Thread(LPVOID pParam)
{
	// 将参数转换为对话框类指针  
	CDETECTDlg* pThis = reinterpret_cast<CDETECTDlg*>(pParam);

	pThis->Show();

	// 线程结束，返回0  
	return 0;
}

UINT Getframe_Thread(LPVOID pParam)
{
	// 将参数转换为对话框类指针  
	CDETECTDlg* pThis = reinterpret_cast<CDETECTDlg*>(pParam);

	pThis->Getframe();

	// 线程结束，返回0  
	return 0;
}

// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()

BEGIN_EASYSIZE_MAP(CDETECTDlg, CDialogEx)
	EASYSIZE(IDC_SHOW, ES_BORDER, ES_BORDER, ES_BORDER, ES_BORDER, 0)
	//EASYSIZE(IDC_EDIT5, ES_BORDER, ES_KEEPSIZE, ES_KEEPSIZE, ES_BORDER, 0)
	
END_EASYSIZE_MAP


// CDETECTDlg 对话框



CDETECTDlg::CDETECTDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_DETECT_DIALOG, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CDETECTDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_slide_ang, name_IDC_slide_ang);
	DDX_Control(pDX, IDC_angleInput, name_IDC_angleInput);
	DDX_Control(pDX, IDC_savePath, name_IDC_savePath);
	DDX_Control(pDX, IDC_port, name_IDC_port);
}

BEGIN_MESSAGE_MAP(CDETECTDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_SIZE()
	ON_WM_SIZING()
	ON_BN_CLICKED(IDC_isOpen, &CDETECTDlg::OnBnClickedisopen)
	ON_BN_CLICKED(IDC_isDetect, &CDETECTDlg::OnBnClickedisdetect)
	ON_BN_CLICKED(IDC_collectData, &CDETECTDlg::OnBnClickedcollectdata)
	ON_BN_CLICKED(IDC_mode1, &CDETECTDlg::OnBnClickedmode1)
	ON_BN_CLICKED(IDC_mode2, &CDETECTDlg::OnBnClickedmode2)
	ON_NOTIFY(NM_CUSTOMDRAW, IDC_slide_ang, &CDETECTDlg::OnNMCustomdrawslideang)
	ON_EN_CHANGE(IDC_angleInput, &CDETECTDlg::OnEnChangeangleinput)
	ON_EN_CHANGE(IDC_savePath, &CDETECTDlg::OnEnChangesavepath)
	ON_WM_CLOSE()
	ON_BN_CLICKED(IDC_add, &CDETECTDlg::OnBnClickedadd)
	ON_BN_CLICKED(IDC_de, &CDETECTDlg::OnBnClickedde)
END_MESSAGE_MAP()


// CDETECTDlg 消息处理程序

BOOL CDETECTDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码

	INIT_EASYSIZE; // easysize代码

	//设置滑动条相关参数
	name_IDC_slide_ang.SetRange(-90, 90);
	name_IDC_slide_ang.SetTicFreq(1);
	name_IDC_slide_ang.SetPos(0);

	//初始选择模式1
	((CButton*)GetDlgItem(IDC_mode1))->SetCheck(true);

	//端口号组件初始化
	// 向组合框中添加数字
	for (int i = 0; i <= 2; ++i)
	{
		CString str;
		str.Format(_T("%d"), i); // 将整数转换为CString类型的字符串  
		name_IDC_port.AddString(str); // 将字符串添加到组合框中  
	}

	// 将组合框的默认选择设为第一项（即数字0）  
	name_IDC_port.SetCurSel(0);

	//detector初始化
	detector.Init(
		"C://modulefile//GLEgeunetAllV4.pt", // module_GL path.
		"C://modulefile//GBEgeunetAllV3.pt", // module_GB path.
		2,  // Scale of speed, range in [1,16], Smaller Faster.
		true,  // Select Camera when true.
		-1  // Camera ID (取-1时为采集卡采集数据，同时前置参数需要设置为true)
	);

	//小窗参数初始化
	pDc = GetDlgItem(IDC_SHOW)->GetDC();

	//编辑区参数读取
	std::ifstream infile;
	std::string buf;
	std::vector<std::string> files = {
		"infChannel.txt", //0
		"infID.txt", //1
		"infPerson.txt", //2
		"infAngle.txt", //3
		"infSavaPath.txt", //4
	};

	infile.open("C://softlib//" + files[0], std::ios::in);
	if (infile.is_open())
	{
		while (getline(infile, buf))
		{
			CString cbuf = CA2T(buf.c_str());
			GetDlgItem(IDC_channel)->SetWindowText(cbuf);
		}
	}
	infile.close();

	infile.open("C://softlib//" + files[1], std::ios::in);
	if (infile.is_open())
	{
		while (getline(infile, buf))
		{
			CString cbuf = CA2T(buf.c_str());
			GetDlgItem(IDC_ID)->SetWindowText(cbuf);
		}
	}
	infile.close();

	infile.open("C://softlib//" + files[2], std::ios::in);
	if (infile.is_open())
	{
		while (getline(infile, buf))
		{
			CString cbuf = CA2T(buf.c_str());
			GetDlgItem(IDC_person)->SetWindowText(cbuf);
		}
	}
	infile.close();

	infile.open("C://softlib//" + files[3], std::ios::in);
	if (infile.is_open())
	{
		while (getline(infile, buf))
		{
			CString cbuf = CA2T(buf.c_str());
			GetDlgItem(IDC_angleInput)->SetWindowText(cbuf);
		}
	}
	infile.close();

	infile.open("C://softlib//" + files[4], std::ios::in);
	if (infile.is_open())
	{
		while (getline(infile, buf))
		{
			CString cbuf = CA2T(buf.c_str());
			GetDlgItem(IDC_savePath)->SetWindowText(cbuf);
		}
	}
	infile.close();

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CDETECTDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CDETECTDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CDETECTDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CDETECTDlg::OnSize(UINT nType, int cx, int cy)
{
	CDialogEx::OnSize(nType, cx, cy);

	// TODO: 在此处添加消息处理程序代码

	UPDATE_EASYSIZE;
}


void CDETECTDlg::OnSizing(UINT fwSide, LPRECT pRect)
{
	CDialogEx::OnSizing(fwSide, pRect);

	// TODO: 在此处添加消息处理程序代码

	EASYSIZE_MINSIZE(600, 200, fwSide, pRect); // easysize代码
}


void CDETECTDlg::OnBnClickedisopen()
{
	// TODO: 在此添加控件通知处理程序代码

	// 开启设备
	if (detector.isOpen) {
		MessageBox(_T("已启用"), _T("提示"), MB_OK | MB_ICONERROR);
	}
	else {
		// 获取端口号
		int port = name_IDC_port.GetCurSel();
		detector.openCapture("F://Desktop//glgb//code//python//video//1.avi", port);


		if (detector.isOpen) {
			hThread1 = AfxBeginThread(Getframe_Thread, this);
			Sleep(500);
			hThread2 = AfxBeginThread(Show_Thread, this);
		}
		// 启用失败
		else {
			char buffer[256];

			// 使用sprintf_s构建格式化字符串  
			sprintf_s(buffer, "端口 %d 打开失败", port);

			// 显示消息框  
			MessageBox(buffer, "提示", MB_OK | MB_ICONERROR);
		}

	}
}

void CDETECTDlg::OnBnClickedisdetect()
{
	// TODO: 在此添加控件通知处理程序代码

	if (detectCheck) {
		detectCheck = false;
		GetDlgItem(IDC_isDetect)->SetWindowText("开启检测");
	}
	else {
		detectCheck = true;
		GetDlgItem(IDC_isDetect)->SetWindowText("关闭检测");
	}
}


void CDETECTDlg::OnBnClickedcollectdata()
{
	// TODO: 在此添加控件通知处理程序代码

	if (detector.isOpen && detectCheck) {
		if (openCollect && collectDatacount < 20) {
			MessageBox(_T("等待采集完毕"), _T("提示"), MB_OK | MB_ICONERROR);
		}
		else {
			time_t now = time(nullptr);
			// 定义一个struct tm来存储本地时间  
			struct tm timeinfo;
			// 使用localtime_s来避免竞态条件  
			errno_t err = localtime_s(&timeinfo, &now);
			nowTime =
				std::to_string(1900 + timeinfo.tm_year) + "-" +
				std::to_string(1 + timeinfo.tm_mon) + "-" +
				std::to_string(timeinfo.tm_mday) + "-" +
				std::to_string(timeinfo.tm_hour) + "-" +
				std::to_string(timeinfo.tm_min) + "-" +
				std::to_string(timeinfo.tm_sec);

			//nowTime =
			//	std::to_string(1900 + timeinfo.tm_year) + "-" +
			//	std::to_string(1 + timeinfo.tm_mon) + "-" +
			//	std::to_string(timeinfo.tm_mday);

			str[64];
			nChars = GetDlgItemText(IDC_channel, str, _countof(str));
			str[nChars] = '\0';
			std::string channel(str);
			nChars = GetDlgItemText(IDC_ID, str, _countof(str));
			str[nChars] = '\0';
			std::string ID(str);
			nChars = GetDlgItemText(IDC_person, str, _countof(str));
			str[nChars] = '\0';
			std::string person(str);

			std::string fileName = ID + "-" + channel + "-" + person + "-" + nowTime;

			if (savepath == "") {
				const int MAXPATH = 250;
				char buffer[MAXPATH];
				_getcwd(buffer, MAXPATH);
				std::string strpath(buffer);
				file_name = strpath + "/" + fileName + ".txt";
			}
			else {
				file_name = savepath + "/" + fileName + ".txt";
			}
			

			std::ofstream outputFile(file_name);
			// 关闭文件  
			outputFile.close();
			openCollect = true;
		}
	}
	else {
		MessageBox(_T("未开启设备或检测"), _T("提示"), MB_OK | MB_ICONERROR);
	}
}


void CDETECTDlg::OnNMCustomdrawslideang(NMHDR* pNMHDR, LRESULT* pResult)
{
	LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);
	// TODO: 在此添加控件通知处理程序代码

	*pResult = 0;

	ang = name_IDC_slide_ang.GetPos();
	std::string s_ang = std::to_string(ang);
	CString cs_ang = CA2T(s_ang.c_str());
	GetDlgItem(IDC_angleInput)->SetWindowText(cs_ang);
}


void CDETECTDlg::OnBnClickedmode1()
{
	// TODO: 在此添加控件通知处理程序代码

	detector.mode = 1;
}


void CDETECTDlg::OnBnClickedmode2()
{
	// TODO: 在此添加控件通知处理程序代码

	detector.mode = 2;
}


void CDETECTDlg::OnEnChangeangleinput()
{
	// TODO:  如果该控件是 RICHEDIT 控件，它将不
	// 发送此通知，除非重写 CDialogEx::OnInitDialog()
	// 函数并调用 CRichEditCtrl().SetEventMask()，
	// 同时将 ENM_CHANGE 标志“或”运算到掩码中。

	// TODO:  在此添加控件通知处理程序代码

	CString strInfo;
	name_IDC_angleInput.GetWindowText(strInfo);
	int nLength = strInfo.GetLength();
	name_IDC_angleInput.SetSel(nLength, nLength, FALSE);
	name_IDC_angleInput.SetFocus();

	if (nLength && strInfo != "-") {
		
		ang = std::atoi(strInfo);
		name_IDC_slide_ang.SetPos(ang);
	}
}


void CDETECTDlg::OnEnChangesavepath()
{
	// TODO:  如果该控件是 RICHEDIT 控件，它将不
	// 发送此通知，除非重写 CDialogEx::OnInitDialog()
	// 函数并调用 CRichEditCtrl().SetEventMask()，
	// 同时将 ENM_CHANGE 标志“或”运算到掩码中。

	// TODO:  在此添加控件通知处理程序代码

	CString strInfo;
	name_IDC_savePath.GetWindowText(strInfo);
	int nLength = strInfo.GetLength();
	name_IDC_savePath.SetSel(nLength, nLength, FALSE);
	name_IDC_savePath.SetFocus();

	savepath = strInfo;
}


void CDETECTDlg::OnClose()
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值

	// 终止进行
	RUNNING = false;
	Sleep(200);

	//// 强制终止线程  
	//TerminateThread(hThread1, 0);
	//TerminateThread(hThread2, 0);
	//// 关闭线程句柄  
	//CloseHandle(hThread1);
	//CloseHandle(hThread2);

	// 编辑区参数保存
	std::ofstream outfile;
	std::string buf;
	std::vector<std::string> files = {
		"infChannel.txt", //0
		"infID.txt", //1
		"infPerson.txt", //2
		"infAngle.txt", //3
		"infSavaPath.txt", //4
	};

	str[64];
	nChars = GetDlgItemText(IDC_channel, str, _countof(str));
	str[nChars] = '\0';
	std::string channel(str);
	outfile.open("C://softlib//" + files[0], std::ios::out);
	if (outfile.is_open())
	{
		outfile << channel << std::endl;
	}
	outfile.close();


	str[64];
	nChars = GetDlgItemText(IDC_ID, str, _countof(str));
	str[nChars] = '\0';
	std::string id(str);
	outfile.open("C://softlib//" + files[1], std::ios::out);
	if (outfile.is_open())
	{
		outfile << id << std::endl;
	}
	outfile.close();

	str[64];
	nChars = GetDlgItemText(IDC_person, str, _countof(str));
	str[nChars] = '\0';
	std::string person(str);
	outfile.open("C://softlib//" + files[2], std::ios::out);
	if (outfile.is_open())
	{
		outfile << person << std::endl;
	}
	outfile.close();

	str[64];
	nChars = GetDlgItemText(IDC_angleInput, str, _countof(str));
	str[nChars] = '\0';
	std::string angle(str);
	outfile.open("C://softlib//" + files[3], std::ios::out);
	if (outfile.is_open())
	{
		outfile << angle << std::endl;
	}
	outfile.close();

	str[64];
	nChars = GetDlgItemText(IDC_savePath, str, _countof(str));
	str[nChars] = '\0';
	std::string savepath(str);
	outfile.open("C://softlib//" + files[4], std::ios::out);
	if (outfile.is_open())
	{
		outfile << savepath << std::endl;
	}
	outfile.close();




	CDialogEx::OnClose();
}


void CDETECTDlg::OnBnClickedadd()
{
	// TODO: 在此添加控件通知处理程序代码

	detector.N_threshold += 3;
	detector.N_threshold = 150 <= detector.N_threshold ? 150 : detector.N_threshold;
}


void CDETECTDlg::OnBnClickedde()
{
	// TODO: 在此添加控件通知处理程序代码

	detector.N_threshold -= 3;
	detector.N_threshold = 15 >= detector.N_threshold ? 0 : detector.N_threshold;
}


BOOL CDETECTDlg::PreTranslateMessage(MSG* pMsg)
{
	// TODO: 在此添加专用代码和/或调用基类

	if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_ESCAPE)
	{
		// 如果消息是键盘按下事件，且是Esc键，执行以下代码（什么都不做，你可以自己添加想要的代码）
		return TRUE;
	}
	if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_RETURN)
	{
		// 如果消息是键盘按下事件，且是Entert键，执行以下代码（什么都不做，你可以自己添加想要的代码）
		return TRUE;
	}

	return CDialogEx::PreTranslateMessage(pMsg);
}
